package com.mes.web.controller.yzl;

import com.mes.entity.hpf.SaleOutDetail;
import com.mes.entity.hpf.SalePlanDetail;
import com.mes.entity.hpf.SaleReturnDetail;
import com.mes.entity.tdd.Staff;
import com.mes.entity.yzl.Condition;
import com.mes.entity.yzl.ListBack;
import com.mes.entity.yzl.OutLib;
import com.mes.entity.yzl.ProContactOrder;
import com.mes.entity.yzl.ReturnOrder;
import com.mes.entity.yzlExtend.ExtendProductor;
import com.mes.entity.yzlExtend.ExtendReturnOdrer;
import com.mes.service.yzl.ReturnService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/yzl")
public class ReturnController {

    protected Logger logger = Logger.getLogger(ReturnController.class);
    private static final long serialVersionUID = 8550329576989690578L;

    @Resource
    ReturnService returnService;

    //生成编号
    @RequestMapping("/returnNumLast")
    public @ResponseBody Map returnNumLast(HttpSession session){
    	Map map = new HashMap();
        String returnNumber = "";
        String returnNumberDate = "";
        DateFormat format = new SimpleDateFormat("yyyyMMdd");
        returnNumberDate = format.format(new Date());
        returnNumber = "T" + returnNumberDate+"00001";

        for(int i=1;i<=99999;i++){
            int dedaoNumber = returnService.checkNumUnique(returnNumber);
            if(dedaoNumber == 0){
                break;
            }else{
                switch (String.valueOf(i).length()){
                    case 1 : returnNumber = "T"+returnNumberDate+"0000"+i;break;
                    case 2 : returnNumber = "T"+returnNumberDate+"000"+i; break;
                    case 3 : returnNumber = "T"+returnNumberDate+"00"+i; break;
                    case 4 : returnNumber = "T"+returnNumberDate+"0"+i; break;
                    case 5 : returnNumber = "T"+returnNumberDate+i; break;
                    default : returnNumber = "T"+returnNumberDate+"1000"+i; break;
                }
                //returnNumber = returnNumber + "00" + i;//以后改进
            }
        }
        map.put("returnNumber", returnNumber);
        Staff staff = (Staff) session.getAttribute("staff");
        map.put("staff", staff);
        return map;
    }

    //条件查询
    @RequestMapping("/returnList")
    public @ResponseBody ListBack returnList(Condition condition){
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        ListBack listBack = new ListBack();
        List<ExtendReturnOdrer> extendReturnOdrers = new ArrayList<>();

        //查询条件处理
        Sup sup = new Sup();
        condition = sup.tdSet(condition);

        //条件查询总数
        int count = returnService.returnListCount(condition);
        listBack.setTotal(count);
        //条件分页查询
        extendReturnOdrers = returnService.listReturnOrder(condition);
        listBack.setRows(extendReturnOdrers);


        return listBack;
    }
    
    //条件查询
    @RequestMapping("/outList")
    public @ResponseBody ListBack outList(Condition condition){
    	DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    	ListBack listBack = new ListBack();
    	List<ExtendProductor> extendReturnOdrers = new ArrayList<>();
    	
    	//查询条件处理
    	Sup sup = new Sup();
    	condition = sup.tdSet(condition);
    	
    	//条件查询总数
    	int count = returnService.outCount(condition);
    	listBack.setTotal(count);
    	//条件分页查询
    	extendReturnOdrers = returnService.outList(condition);
    	listBack.setRows(extendReturnOdrers);
    	
    	
    	return listBack;
    }
    
    //添加退货单的出库详情
    @RequestMapping("/addOutOrderXq")
    public @ResponseBody List<ExtendProductor> addOutOrderXq(long id){
    	List<ExtendProductor> extendProductors = new ArrayList<>();
        extendProductors = returnService.addOutOrderXq(id);
        return extendProductors;
    }

    @RequestMapping("/findReturnById")
    public @ResponseBody ExtendReturnOdrer findReturnById(long id){
        ExtendReturnOdrer extendReturnOdrer = new ExtendReturnOdrer();
        extendReturnOdrer = returnService.findReturnById(id);
        return extendReturnOdrer;
    }

    //详情
    @RequestMapping("/returnXq")
    public @ResponseBody List<SaleReturnDetail> returnXq(long id){
        List<SaleReturnDetail> saleReturnDetails = new ArrayList<>();
        saleReturnDetails = returnService.returnDetail(id);
        return saleReturnDetails;
    }
    //添加
    @RequestMapping("/addReturnfrom")
    public @ResponseBody int addReturnfrom(@RequestBody Object obj) throws ParseException {
        int isSuccess = 0;

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonObject = JSONObject.fromObject(obj);
        JSONArray jsonArray = jsonObject.getJSONArray("productors");

        //新增退库单
        ReturnOrder returnOrder = new ReturnOrder();
        returnOrder.setCustomerId(Integer.valueOf((String)jsonObject.get("customerId")));
        returnOrder.setEntryPerson(Integer.valueOf((String)jsonObject.get("entryPerson")));
        returnOrder.setReturnsDate((new java.sql.Date(simpleDateFormat.parse((String)jsonObject.get("planDate")).getTime())));
        returnOrder.setReturnsExamineStatus("0");
        returnOrder.setReturnsStatus("0");
        returnOrder.setReturnsNumber((String)jsonObject.get("number"));
        long isaddReturn = returnService.addReturn(returnOrder);

        if(isaddReturn > 0){
            for(int i = 0;i<jsonArray.size();i++){
                JSONObject jObj = (JSONObject) jsonArray.get(i);
                int returnQ = jObj.getInt("returnQ");
                int lastOutQ = jObj.getInt("lastOutQ");
                SaleReturnDetail saleReturnDetail = new SaleReturnDetail();
                saleReturnDetail.setProductorId(jObj.getLong("pid"));
                saleReturnDetail.setReturnQ(returnQ);
                saleReturnDetail.setLastOutQ(lastOutQ);
                saleReturnDetail.setReturnLibId(isaddReturn);
                saleReturnDetail.setReturnReason(jObj.getString("returnReason"));
                saleReturnDetail.setOutDetailId(jObj.getLong("outId"));
                returnService.addReturnDetail(saleReturnDetail);
                if (lastOutQ == returnQ) {
                	SaleOutDetail saleOutDetail = new SaleOutDetail();
                	saleOutDetail.setLastOutQ(lastOutQ-returnQ);
                	saleOutDetail.setAddReturnIsSelect("1");
                	saleOutDetail.setId(jObj.getLong("outId"));
                	returnService.updateOutDetailStatus(saleOutDetail);
				} else {
					SaleOutDetail saleOutDetail = new SaleOutDetail();
                	saleOutDetail.setLastOutQ(lastOutQ-returnQ);
                	saleOutDetail.setAddReturnIsSelect("0");
                	saleOutDetail.setId(jObj.getLong("outId"));
                	returnService.updateOutDetailStatus(saleOutDetail);
				}
            }
            isSuccess = 1;
        }
        return isSuccess;
    }

    //修改
    @RequestMapping("/updateReturnFrom")
    public @ResponseBody int updateReturnFrom(@RequestBody Object obj) throws ParseException{
        int isSuccess = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonObject = JSONObject.fromObject(obj);

        JSONArray jsonArray = jsonObject.getJSONArray("productors");

        System.out.println(jsonObject);
        System.out.println(jsonArray);
        //先去更新退货单
        ReturnOrder returnOrder = new ReturnOrder();
        returnOrder.setId(jsonObject.getLong("id"));
        returnOrder.setCustomerId(Integer.valueOf((String)jsonObject.get("customerId")));
        returnOrder.setEntryPerson(Integer.valueOf((String)jsonObject.get("entryPerson")));
        returnOrder.setReturnsDate((new java.sql.Date(simpleDateFormat.parse((String)jsonObject.get("planDate")).getTime())));
        long updateIsSuccess = 0;
        updateIsSuccess = returnService.updateReturn(returnOrder);


        if(updateIsSuccess > 0){
            //更新对应的产品  暂时不可以添加产品或者删除产品
            for(int i = 0;i<jsonArray.size();i++){
                JSONObject jObj = (JSONObject) jsonArray.get(i);
                int oldReturnQ = jObj.getInt("returnQ");
                int returnQ = jObj.getInt("planQ");
                int lastOutQ = jObj.getInt("lastOutQ");
                int rLastOutQ = jObj.getInt("rLastOutQ");
                SaleReturnDetail saleReturnDetail = new SaleReturnDetail();
                saleReturnDetail.setId(jObj.getLong("id"));
                saleReturnDetail.setReturnQ(returnQ);
                saleReturnDetail.setLastOutQ(lastOutQ);
                saleReturnDetail.setReturnReason(jObj.getString("returnReason"));
                returnService.updateReturnDetail(saleReturnDetail);
                if ((oldReturnQ+rLastOutQ) == returnQ) {
                	SaleOutDetail saleOutDetail = new SaleOutDetail();
                	saleOutDetail.setLastOutQ(oldReturnQ+rLastOutQ-returnQ);
                	saleOutDetail.setAddReturnIsSelect("1");
                	saleOutDetail.setId(jObj.getLong("outDetailId"));
                	returnService.updateOutDetailStatus(saleOutDetail);
				} else {
					SaleOutDetail saleOutDetail = new SaleOutDetail();
                	saleOutDetail.setLastOutQ(oldReturnQ+rLastOutQ-returnQ);
                	saleOutDetail.setAddReturnIsSelect("0");
                	saleOutDetail.setId(jObj.getLong("outDetailId"));
                	returnService.updateOutDetailStatus(saleOutDetail);
				}
                //logger.info("jObj---------"+jObj);
                returnService.updateReturnDetail(saleReturnDetail);
            }
            isSuccess = 1;
        }

        return isSuccess;
    }
    
    /***
     * 2018/3/25
     * 侯鹏飞
     * @param ids
     * @return
     */
    //批量删除
    @RequestMapping("/deleteReturn")
    public @ResponseBody int deleteReturn(@RequestParam(value = "arr") String arr){
    	List<Integer> list = new ArrayList<>();
        list = JSONArray.toList(JSONArray.fromObject(arr));
    	int isSuccess = 0;
        for(int i=0;i<list.size();i++) {
        	//删除销售计划
            int deleteOrder = returnService.deleteReturn(list.get(i));
            
            if (deleteOrder>0) {
            	
            	returnService.deleteReturnDetail(list.get(i));
            }
            
            isSuccess = deleteOrder;
        }
        return isSuccess;
    }
    
    /***
     * 侯鹏飞
     * 2018/3/25
     * @param arr
     * @return
     */
    //提交审核
    @RequestMapping("/returnApproveds")
    public @ResponseBody int returnApproveds(@RequestParam(value = "arr") String arr){

        List<Integer> list = new ArrayList<>();
        list = JSONArray.toList(JSONArray.fromObject(arr));
        int isSuccess = 0;
        isSuccess = returnService.returnApproveds(list);
        return isSuccess;
    }

    /***
     * 侯鹏飞
     * 2018/3/25
     * @param arr
     * @return
     */
    //撤销审核
    @RequestMapping("/returnUnApproveds")
    public @ResponseBody int returnUnApproveds(@RequestParam(value = "arr") String arr){
        List<Integer> list = new ArrayList<>();
        list = JSONArray.toList(JSONArray.fromObject(arr));
        int isSuccess = 0;
        isSuccess = returnService.returnUnApproveds(list);
        return isSuccess;
    }
    
    /***
     * 侯鹏飞
     * 2018/3/25
     * @param arr
     * @return
     */
    //退货处理
    @RequestMapping("/returnProcess")
    public @ResponseBody int returnProcess(@RequestParam(value = "arr") String arr){

        List<Integer> list = new ArrayList<>();
        list = JSONArray.toList(JSONArray.fromObject(arr));
        int isSuccess = 0;
        isSuccess = returnService.returnsProcess(list);
        return isSuccess;
    }
    
    /***
     * 侯鹏飞
     * 2018/3/25
     * @return
     * @throws IOException
     */
	//导出
    @RequestMapping("/returnImport")
    public void returnImport(HttpServletResponse response) throws IOException{
        List<ReturnOrder> returnOrderList = returnService.returnOrderList();
        String[] headers = { "序号" ,"退货编号", "退货日期", "客户", "状态", "审批状态" };
	 	//创建HSSFWorkbook对象(excel的文档对象)
	 	Workbook wb=new XSSFWorkbook();
	 	//建立新的sheet对象（excel的表单）
	 	Sheet sheet=wb.createSheet("销售退货表");
	 	// 设置表格默认列宽度
        sheet.setDefaultColumnWidth(40);  
        // 产生表格标题行  
        Row row=sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {  
        	row.createCell(i).setCellValue(headers[i]);
        }
		for (int i = 0; i < returnOrderList.size(); i++) {
			Row row2=sheet.createRow(i+1);
			row2.createCell(0).setCellValue(i+1);
			row2.createCell(1).setCellValue(returnOrderList.get(i).getReturnsNumber());
			row2.createCell(2).setCellValue(returnOrderList.get(i).getReturnsDate().toString());
			row2.createCell(3).setCellValue(returnOrderList.get(i).getName());
			if (returnOrderList.get(i).getReturnsStatus().equals("0")) {
				row2.createCell(4).setCellValue("处理中");
			} else {
				row2.createCell(4).setCellValue("已处理");
			}
			if (returnOrderList.get(i).getReturnsExamineStatus().equals("0")) {
				row2.createCell(5).setCellValue("未提交审核");
			} else if (returnOrderList.get(i).getReturnsExamineStatus().equals("1")) {
				row2.createCell(5).setCellValue("审核中");
			} else {
				row2.createCell(5).setCellValue("审核通过");
			}
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String nowtime = sdf.format(new Date());
		String fileName = nowtime+"销售退货表.xlsx";
		fileName = new String(fileName.getBytes("GBK"), "iso8859-1");
		try {
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename="
					+ fileName);
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			OutputStream output = response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(
					output);
			bufferedOutPut.flush();
			wb.write(bufferedOutPut);
			bufferedOutPut.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}
